//
//  PhotosView.swift
//  开心微博
//
//  Created by 郑开心 on 15/12/16.
//  Copyright © 2015年 郑开心. All rights reserved.
//

import UIKit
import AlamofireImage

class PhotosView: UIImageView,PhotoViewDelegate {
    
    var pic_urls : [Photo]?{
        didSet{
            setPic_urls()
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.userInteractionEnabled = true
        //self.backgroundColor = UIColor.redColor()
        self.setUpAllChindView()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setUpAllChindView(){
        for var i = 0;i < 9;i++ {
            let imageV = PhotoView(frame: CGRectMake(0, 0, 0, 0))
            //print(imageV.userInteractionEnabled)
            imageV.tag = i
            imageV.delegate = self
            self.addSubview(imageV)
        }
    }
    
    func setPic_urls(){
        if let pic_urls = pic_urls {
            let count = self.subviews.count
            for var i = 0;i < count;i++ {
                let imageV = self.subviews[i] as! PhotoView
                
                if i < pic_urls.count {
                    let photo = pic_urls[i]
                    imageV.hidden = false
                    imageV.photo = photo
                    
                }else {
                    imageV.hidden = true
                }
            }

        }
    }
    
    func PhotoViewDidClick(view: PhotoView) {
        let brower = MJPhotoBrowser()
        var i : Int32 = 0
        var mjs = [MJPhoto]()
        for photo in pic_urls! {
            let p = MJPhoto()
            
            p.url = photo.thumbnail_pic_big
            p.index = i
            p.srcImageView = view
            mjs.append(p)
            i++
            
        }
        brower.photos = mjs
        brower.currentPhotoIndex = UInt(view.tag)
        brower.show()
    }
    
    
    
    override func layoutSubviews() {
        super.layoutSubviews()
        if let pic_urls = pic_urls {
            
            var x : CGFloat = 0
            var y : CGFloat = 0
            var wh : CGFloat = Coant.photoWH
            let margin : CGFloat = 10
            var col = 0
            var rol = 0
            let cols = pic_urls.count==4 ? 2 :  3
            if pic_urls.count % 3 == 0{
                wh = (Coant.ScreenW - 4 * 10) / 3
            }
            for var i = 0;i < pic_urls.count;i++ {
                let imageV = self.subviews[i] as! PhotoView
                col = i % cols
                rol = i / cols
                x = CGFloat(col) * (wh + margin)
                y = CGFloat(rol) * (wh + margin)
                imageV.frame = CGRectMake(x, y, wh, wh)
            }
        }else{
            for var i = 0;i < 9 ;i++ {
                let imageV = self.subviews[i] as! PhotoView
                imageV.frame = CGRectMake(0, 0, 0, 0)
            }
        }
    }
}
